//
//  VenusMyViewController.swift
//  Venus
//
//  Created by qurongxiang on 2018/7/23.
//  Copyright © 2018年 zhaowang. All rights reserved.
//

import UIKit
import MJRefresh
import SwiftyJSON
private let cellID = "cellID"


class ClientVenusMyViewController: UIViewController {
    fileprivate lazy var titleLabel = UILabel(UIColor.white, 20, "个人中心")
    var topImageView:UIImageView!
    var imageHeight:CGFloat = 200 - 20
    var itemWidth:CGFloat = 80
    var numModel:ShowNumModel =  ShowNumModel()
    var userModel:MyUserModel =  MyUserModel()
    fileprivate lazy var topView =  ClientMyTopView(frame: CGRect.zero)
    fileprivate var modelArr = [
        ["title":"我的收藏","img":"my_collection"],
        ["title":"消息通知","img":"my_message"],
        ["title":"我的预约","img":"my_yuyue"],
        ["title":"话题管理","img":"my_tip"],
        ["title":"小组管理","img":"my_group"],
        ["title":"用户反馈","img":"my_feedback"],
        ["title":"系统设置","img":"my_setting"]
    ]
    
    fileprivate lazy var collectionView : UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 40
        layout.minimumInteritemSpacing = CGFloat(Int((kScreenW - (itemWidth*3) - 60) / 2))
        layout.scrollDirection = .vertical
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(MyCollectionViewCell.self, forCellWithReuseIdentifier: cellID)
        collectionView.scrollsToTop = false
        collectionView.showsHorizontalScrollIndicator = true
        collectionView.contentInset = UIEdgeInsets(top: 0, left: 30, bottom: 0, right: 30)
        collectionView.alwaysBounceVertical = true
        return collectionView
    }()
    
    fileprivate lazy var currentApplybtn =  UIButton(type: .custom)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadData(false)
        requestMy()
    }
}

// MARK: - 点击交互
extension ClientVenusMyViewController: UITextFieldDelegate {
    func updateUser(userName:String ,headImg:String ) {
        let url = kHost + kupdateUser + "".apiF(time: "1", sign: "1")
        var dict = ["k":"v"]
        
        if userName.count != 0 {
            dict = ["userName":userName,
                    "id":String(UserInfo.shareInstance.userModel().id)
            ]
        }else {
            dict = ["headImg":headImg,
                    "id":String(UserInfo.shareInstance.userModel().id)
            ]
        }
        
        self.hudLoad()
        TempNetTool.post(url, parameters: dict, progress: nil, success: { [weak self](result) in
            self?.hudHide()
            self?.hudLoadMessage("修改成功")
        }) { [weak self](error) in
            self?.hudHide()
            self?.hudError()
        }
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        self.userModel.userName = textField.text!
        if textField.text?.count == 0 {
            self.hudLoadMessage("昵称不要为空哦")
            textField.text = "乐优学"
            self.userModel.userName = "乐优学"
        }else {
            updateUser(userName: self.userModel.userName, headImg: "") //改名字
        }
    }
    
    //姓名
    @objc func clickName() {
        topView.titleLabel.becomeFirstResponder()
        topView.titleLabel.delegate = self
    }
    
    //上传头像
    @objc func dismissMenu() {
        let uploadAlertController = UIAlertController(title:nil, message: nil, preferredStyle:UIAlertController.Style.actionSheet)
        
        let takePhoto = UIAlertAction(title:"拍照", style:UIAlertAction.Style.default) { (action:UIAlertAction)in
            self.openCamera()
            
        }
        let photoLib = UIAlertAction(title:"从相册选择", style:UIAlertAction.Style.default) { (action:UIAlertAction)in
            self.openPhoto()
        }
        
        let cancel = UIAlertAction(title:"取消", style:UIAlertAction.Style.cancel) { (action:UIAlertAction)in
        }
        
        uploadAlertController.addAction(takePhoto)
        uploadAlertController.addAction(photoLib)
        uploadAlertController.addAction(cancel)
        present(uploadAlertController, animated: true, completion: nil)
    }
    
    ///申请
    @objc func clickApplyBtn(btn:UIButton) {
        if userModel.jobName.count > 0 {hudLoadMessage("已经审核成功"); return }else {
            if userModel.haveApply {  hudLoadMessage("急速审核中,请稍后!"); return }
        }
        let vc = ApplyAuthenticationViewController()
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    /// 兑换
    @objc func clickBtn(btn:UIButton) {
        
        if numModel.shareNum < 5 { hudLoadMessage("兑换数量不够") ; return }
        
        let alertController = UIAlertController(title: "系统提示",
                                                message: "您确定要兑换吗？", preferredStyle: .alert)
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        let okAction = UIAlertAction(title: "确定", style: .default, handler: { action in
            self.hudLoad()
            TempNetTool.post(kHost + kexchangeSeeNum + "".apiF(time: "1", sign: "1"), parameters: nil , progress: nil, success: { [weak self](result) in
                self?.hudHide()
                self?.loadData(false)
            }) { [weak self](error) in
                self?.hudHide()
                self?.hudLoadMessage("兑换失败")
            }
        })
        alertController.addAction(cancelAction)
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)
        
        
    }
}

// MARK: - 网络请求
extension ClientVenusMyViewController {
    func loadData(_ showLoad:Bool) {
        topView.start()
        let userModel = UserInfo.shareInstance.userModel()
        let dict = ["userId":(userModel.id),
                    "role":(userModel.role),
                    "msgType":"00",
                    "timestamp":"1",
                    "sign":"1"
            ] as [String : Any]
        if showLoad { self.hudLoad() }
        TempNetTool.get(kHost + kqueryMsgNum , parameters: dict, progress: nil, success: { [weak self](result) in
            self?.hudHide()
            let json = JSON(result as Any)
            let mynumModel = ShowNumModel(fromJson: json["data"])
            self?.numModel = mynumModel
            self?.showNum()
            
            self?.collectionView.reloadData()
            self?.collectionView.mj_header.endRefreshing()
            self?.topView.stop()
        }) { [weak self](error) in
            self?.hudHide()
            self?.topView.stop()
            self?.collectionView.mj_header.endRefreshing()
        }
    }
    
    
    func requestMy() {
        TempNetTool.get(kHost + kinitMy + "".apiF(time: "1", sign: "2"), parameters: nil, progress: nil, success: { [weak self] (result) in
            let json = JSON(result as Any)
            self?.userModel = MyUserModel(fromJson: json)
            self?.topView.configModel(userModel: self?.userModel ?? MyUserModel())
        }) { (error) in
            
        }
    }
    
    func showNum() {
        
        
        
        self.tabBarController?.tabBar.showBadgeOnItemIndex(index: 0)
    }
}

// MARK: - 滑动监听
extension ClientVenusMyViewController :UIScrollViewDelegate{
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let point = scrollView.contentOffset
        
        if point.y < 0 {
            topImageView.height = imageHeight - point.y
        }else {
            topImageView.height = imageHeight
        }
    }
}

// MARK: - 代理
extension ClientVenusMyViewController: UICollectionViewDelegate , UICollectionViewDataSource ,UICollectionViewDelegateFlowLayout {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return modelArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! MyCollectionViewCell
        cell.congfigModel(modelArr: modelArr, index: indexPath , numModel:numModel)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: itemWidth, height: 85)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if self.modelArr[indexPath.item]["title"] == "我的收藏"{
            let vc = MyCollectionVc()
            self.navigationController?.pushViewController(vc, animated: true)
            return
        }
        
        if self.modelArr[indexPath.item]["title"] == "消息通知" {
            let vc = MyMessageVc()
            self.navigationController?.pushViewController(vc, animated: true)
            return
        }
        
        if self.modelArr[indexPath.item]["title"] == "我的预约" { //我的预约
            let userModel = UserInfo.shareInstance.userModel()
            if userModel.role == "0" {
                let vc = InstitutionalAppointmentVC()
                self.navigationController?.pushViewController(vc, animated: true)
            }else if (userModel.role == "1") {
                let vc = ClientAppointmentViewController()
                self.navigationController?.pushViewController(vc, animated: true)
            }else{
                hudLoadMessage("脏数据 , 请重新注册账号 或者登录 role有数据吗")
            }
            return
        }
        
        if self.modelArr[indexPath.item]["title"] == "用户反馈" {
            let vc = MyFeedbackVC()
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
        if self.modelArr[indexPath.item]["title"] == "系统设置" {
            let vc = MysettingVC()
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
        if self.modelArr[indexPath.item]["title"] == "话题管理" {
            let vc = MyTopicVC()
            self.navigationController?.pushViewController(vc, animated: true)
            return
        }
        
        if self.modelArr[indexPath.item]["title"] == "小组管理" {
            let vc = MyGroupVC()
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
    }
}




// MARK: - 设置UI
extension ClientVenusMyViewController {
    func setupUI() {
        
        collectionView.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
            self?.topView.start()
            self?.loadData(false)
        })
        
        
        view.backgroundColor = UIColor.white
        
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(view)
            make.top.equalTo(view).offset(imageHeight + 70)
        }
        collectionView.backgroundColor = UIColor.white
        
        topImageView = UIImageView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenW, height: imageHeight))
        topImageView.image = UIImage.init(named: "myTop")
        
        
        view.addSubview(topImageView)
        view.addSubview(topView)
        view.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(LayoutCommon.navHeight - 45 )
        }
        
        topImageView.contentMode = .scaleAspectFill
        topView.snp.makeConstraints { (make) in
            make.left.equalTo(view).offset(20)
            make.right.equalTo(view).inset(20)
            make.height.equalTo(160)
            make.top.equalTo(view).offset(80)
        }
        topView.backgroundColor = UIColor.white
        topView.layer.shadowColor = UIColor.black.cgColor
        topView.layer.shadowOffset = CGSize(width: 0, height: 0)
        topView.layer.shadowOpacity = 0.5
        topView.layer.shadowRadius = 5
        topView.layer.cornerRadius = 5
        
        
        view.addSubview(currentApplybtn)
        topView.applybtn.addTarget(self, action: #selector(clickApplyBtn(btn:)), for: .touchUpInside)
        currentApplybtn.snp.makeConstraints { (make) in
            make.center.equalTo(topView.applybtn.snp.center)
            make.size.equalTo(CGSize(width: 80, height: 40))
        }
        currentApplybtn.backgroundColor = UIColor.clear
        currentApplybtn.addTarget(self, action: #selector(clickApplyBtn(btn:)), for: .touchUpInside)
        
        let gesture = UITapGestureRecognizer(target: self, action: #selector(dismissMenu))
        let namegesture = UITapGestureRecognizer(target: self, action: #selector(clickName))
        topView.headImgView.addGestureRecognizer(gesture)
        topView.titleLabel.addGestureRecognizer(namegesture)
    }
}


// MARK:-  相机 相册 代理
extension ClientVenusMyViewController: UIImagePickerControllerDelegate ,UINavigationControllerDelegate {
    func openCamera(){
        let pick:UIImagePickerController = UIImagePickerController()
        pick.delegate = self
        pick.sourceType = UIImagePickerController.SourceType.camera
        pick.allowsEditing = true
        present(pick, animated: true, completion: nil)
    }
    
    func openPhoto(){
        let pick:UIImagePickerController = UIImagePickerController()
        pick.delegate = self
        pick.sourceType = UIImagePickerController.SourceType.photoLibrary
        pick.allowsEditing = true
        present(pick, animated: true, completion: nil)
    }
    
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
  
        picker.dismiss(animated: true, completion: nil)
        self.hudLoad()
             guard var img = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else { return }
        img = img.rotate(aImage: img)
        img = img.square(aImage: img)
        let data = img.jpegData(compressionQuality: 0.5)
        TempNetTool.get(kHost + kgetImgToken, parameters: ["timestamp":"11","sign":"22"], progress: nil, success: { (result) in
            let json = JSON(result ?? "")
            let token = json["uptoken"].string
            let upManager = QNUploadManager()
            upManager?.put(data, key: nil, token: token, complete: { [weak self](info, key, resp) in
                self?.hudHide()
                let json = JSON(resp as Any)
                let url = json["key"].stringValue
                if url.count > 0 {
                    self?.topView.headImgView.showImageS(kqnImageHost + url)
                    self?.userModel.headImg = kqnImageHost + url
                    self?.updateUser(userName: "" , headImg: self?.userModel.headImg ?? "") //改头像
                }else {
                    self?.hudLoadMessage("网络异常")
                }
                }, option: nil)
        }) { [weak self](error) in
            self?.hudHide()
            self?.hudLoadMessage("网络异常")
        }
    }
}
